#include "ScriptCallHelp.h"
#include "Common/Item/Item.h"
#include "../Character/npc/Npc.h"
#include "../Character/Player.h"

ScriptCallHelp::ScriptCallHelp(LuaScript* sc) : ScriptSafeCall(sc) 
{
    MMO_ASSERT(sc != nullptr);

	m_pItem = NULL;
	m_pNPC = NULL;
	m_pPlayer = NULL;

    if (sc == nullptr) 
	{
        return;
    }
    
    LuaRef refItem = sc->GetGlobal("it");
    if (refItem.isUserdata())
	{
		m_pItem = refItem.cast<Item*>();
    }

    LuaRef refNpc = sc->GetGlobal("tar");
    if (refNpc.isUserdata()) 
	{
		m_pNPC = refNpc.cast<NPC*>();
    }

    LuaRef refPlayer = sc->GetGlobal("pl");
    if (refPlayer.isUserdata()) 
	{
		m_pPlayer = refPlayer.cast<Player*>();
    }
}

ScriptCallHelp::~ScriptCallHelp() 
{
    Restore();
}

void ScriptCallHelp::Restore()
{
	SetItem(m_pItem);
	SetNPC(m_pNPC);
	SetPlayer(m_pPlayer);
}

void ScriptCallHelp::SetItem(Item* item) 
{
    if (m_script != nullptr) 
	{
        m_script->SetGlobal<Item*>("it", item);
    }
}

void ScriptCallHelp::SetNPC(NPC* npc)
{
    if (m_script != nullptr) 
	{
        m_script->SetGlobal<NPC*>("tar", npc);
    }
}

void ScriptCallHelp::SetPlayer(Player* player) 
{
    if (m_script != nullptr) 
	{
        m_script->SetGlobal<Player*>("pl", player);
    }
}
